//
//  FTToggleSwitchCell.m
//  WebPDA
//
//  Created by Justin Yip on 9/2/10.
//  Copyright 2010 TenNights.com. All rights reserved.
//

#import "FTToggleSwitchCell.h"


@implementation FTToggleSwitchCell
@synthesize switchControl;

#pragma mark -
#pragma mark Cell lifecycle

-(id)initWithBundle:(NSBundle*)bundle valueHolder:(id)object reuseIdentifier:(NSString *)reuseIdentifier {
    if ((self = [super initWithBundle:bundle valueHolder:object reuseIdentifier:reuseIdentifier])) 
	{
        // Initialization code
		switchControl = [[UISwitch alloc] initWithFrame:CELL_APPEND_RECT];
		
		[self.contentView addSubview:switchControl];
    }
    return self;
}

-(void)configureWithObject:(id)kvcObject preferenceSpecifier:(NSDictionary*)ps {
	
	[super configureWithObject:kvcObject preferenceSpecifier:ps];
	
	if([ps objectForKey:@"TrueValue"] != nil)
	{
		trueValue = [ps objectForKey:@"TrueValue"];
	}
	
	if([ps objectForKey:@"FalseValue"] != nil)
	{
		falseValue = [ps objectForKey:@"FalseValue"];
	}
	
	if([ps objectForKey:@"DefaultValue"] != nil)
	{
		id defValue = [ps objectForKey:@"DefaultValue"];
		if ([defValue isEqual:trueValue]) 
		{
			switchControl.on = YES;
		}
		else if([defValue isEqual:falseValue])
		{
			switchControl.on = NO;
		}else 
		{
			//默认值和True值，False值均不匹配
			NSLog(@"DefaultValue[%@] not equals to TrueValue[%@] nor FalseValue[%@]",
				  [ps objectForKey:@"DefaultValue"],
				  trueValue,
				  falseValue);
			abort();
		}
	}
	
	/*
	 set value from entity
	 */
	//getter selector
	NSString *key = [self keyFromPreferenceSpecifier];
	
	if (key && [kvcObject containsValueForKey:key]) {
		if ([[kvcObject valueForKey:key] isEqual:trueValue])
		{
			switchControl.on = YES;
		}
		else if([[kvcObject valueForKey:key] isEqual:falseValue])
		{
			switchControl.on = NO;
		}
		else {
			//取回的值和True值，False值均不匹配
			NSLog(@"savedValue[%@] not equals to TrueValue[%@] nor FalseValue[%@]",
				  [kvcObject valueForKey:key],
				  trueValue,
				  falseValue);
			abort();
		}

	}
}

#pragma mark -
#pragma mark Callback

-(id)getValue {
	return switchControl.on ? trueValue : falseValue;
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated {
	[super setEditing:editing animated:animated];
	switchControl.enabled = editing;
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	[switchControl removeFromSuperview];
	
	[switchControl release];
    [super dealloc];
}


@end
